package com.chain.BrotherExchange.ui.window;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.Quotation;
import com.chain.BrotherExchange.data.model.QuotationTypes;
import com.chain.BrotherExchange.ui.adapter.QuotationListAdapter;
import com.chain.BrotherExchange.viewmodel.QuotationViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.chain.BrotherExchange.widget.CompatPopupWindow;
import com.example.common.widget.state.NetworkStateLayout;

import java.util.List;

/**
 * 行情 popup window
 */
public class QuotationPopupWindow implements RadioGroup.OnCheckedChangeListener, AdapterView.OnItemClickListener {

    private final View mRootView;
    private String mDefaultSymbol;
    private final Fragment mFragment;
    private PopupWindow mPopupWindow;
    private boolean isFirstLoad = true;
    private QuotationListAdapter mListAdapter;
    private final QuotationViewModel mViewModel;
    private NetworkStateLayout mRootStateLayout;
    private NetworkStateLayout mQuestionStateLayout;
    private OnItemClickListener mOnItemClickListener;
    private List<QuotationTypes.DataBean.ListBean> mQuestionTitles;
    private RadioGroup mQuestionTitleGroup;
    private int currentPosition;

    public QuotationPopupWindow(Fragment fragment) {
        this.mFragment = fragment;
        mViewModel = ViewModelProviders.of(fragment).get(QuotationViewModel.class);
        mRootView = LayoutInflater.from(fragment.getContext()).inflate(R.layout.window_quotation,
                null);

        initViews();

        initPopupWindow();
    }

    private void initPopupWindow() {
        mPopupWindow = new CompatPopupWindow(mRootView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        mPopupWindow.setAnimationStyle(R.style.animQuotationPopupWindow);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    public void show(View anchor) {
        mPopupWindow.showAsDropDown(anchor);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.mOnItemClickListener = onItemClickListener;
    }

    private void initViews() {
        mRootStateLayout = mRootView.findViewById(R.id.network_state_layout);
        mQuestionStateLayout = mRootView.findViewById(R.id.question_list_state_layout);
        mQuestionTitleGroup = mRootView.findViewById(R.id.question_title_group);
        mQuestionTitleGroup.setOnCheckedChangeListener(this);
        initQuestionTitle(mQuestionTitleGroup);

        RecyclerView recyclerView = mRootView.findViewById(R.id.recycler_view);
        mListAdapter = new QuotationListAdapter();
        mListAdapter.setItemClickListener(this);
        recyclerView.setAdapter(mListAdapter);

        mQuestionStateLayout.setOnAnewRequestNetworkListener(() -> {
            int id = (int) mQuestionTitleGroup.findViewById(mQuestionTitleGroup
                    .getCheckedRadioButtonId()).getTag();
            load(id);
        });

        mRootView.setOnClickListener(v -> {
            if (mPopupWindow != null && mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            }
        });
    }

    private void initQuestionTitle(RadioGroup group) {
        group.removeAllViews();

        mViewModel.quotationTypes().observe(mFragment, resource ->
                Resource.load(mFragment.getContext(), resource, mRootStateLayout, result -> {
                    this.mQuestionTitles = result;
                    int index = 0;
                    String str = null;
                    if (mDefaultSymbol != null) {
                        str = mDefaultSymbol.split("/")[1];
                    }

                    for (int i = 0; i < result.size(); i++) {
                        QuotationTypes.DataBean.ListBean list = result.get(i);
                        if (str != null && str.equals(list.getMark())) {
                            index = i;
                        }

                        group.addView(createMenuItem(group, list.getMark(), list.getToken_id()));
                    }

                    group.check(group.getChildAt(index).getId());
                })
        );
    }

    private RadioButton createMenuItem(RadioGroup group, String text, int id) {
        RadioButton view = (RadioButton) LayoutInflater.from(mFragment.getContext())
                .inflate(R.layout.layout_question_menu_radio_button, group, false);
        view.setText(text);
        view.setTag(id);
        return view;
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        View view = group.findViewById(checkedId);
        Integer id = (Integer) view.getTag();
        load(id);
    }

    private void load(int id) {
        mViewModel.quotationInfo(id).observe(mFragment, resource ->
                Resource.load(mFragment.getContext(), resource, mQuestionStateLayout, result -> {
                            int index = 0;
                            for (int i = 0; i < result.size(); i++) {
                                Quotation.DataBean.ListBean listBean = result.get(i);
                                listBean.setToken_id(id);
                                if (mDefaultSymbol != null && mDefaultSymbol.equals(listBean.getSymbol())) {
                                    index = i;
                                }
                            }

                            if (isFirstLoad) {
                                isFirstLoad = false;
                                mOnItemClickListener.itemClick(result.get(index));
                            }

                            mListAdapter.setQuotationList(result);
                        }
                )
        );
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mOnItemClickListener.itemClick(mListAdapter.getItem(position));
        this.currentPosition = position;
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
    }

    public void performClick(){
        mOnItemClickListener.itemClick(mListAdapter.getItem(currentPosition));
    }

    public void resetViews() {
        if (mDefaultSymbol != null && mQuestionTitles != null) {
            String str = mDefaultSymbol.split("/")[1];
            for (int index = 0; index < mQuestionTitles.size(); index++) {
                if (str.equals(mQuestionTitles.get(index).getMark())) {
                    RadioButton button = (RadioButton) mQuestionTitleGroup.getChildAt(index);
                    isFirstLoad = true;
                    if (!button.isChecked()) {
                        mQuestionTitleGroup.check(button.getId());
                    } else {
                        int id = mQuestionTitles.get(index).getToken_id();
                        load(id);
                    }

                    break;
                }
            }
        }
    }

    public void setDefaultQuotation(String symbol) {
        this.mDefaultSymbol = symbol;
    }

    public interface OnItemClickListener {
        void itemClick(Quotation.DataBean.ListBean listBean);
    }
}
